package com.yami.shop.coupon.platform.task;

import cn.hutool.core.date.DateUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.common.util.CacheManagerUtil;
import com.yami.shop.coupon.common.dao.CouponMapper;
import com.yami.shop.coupon.common.service.CouponService;
import com.yami.shop.coupon.common.service.CouponUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;



/**
 * 优惠券定时任务
 * //0 0 0/1 * * ?
 * @author lanhai
 */
@Slf4j
@AllArgsConstructor
@Component
public class CouponTask {

    private final CouponUserService couponUserService;
    private final CouponService couponService;
    private final CouponMapper couponMapper;
    private final CacheManagerUtil cacheManagerUtil;


    /**
     * 删除用户失效30天以上的优惠券
     */
    @XxlJob("deleteCouponUser")
    public void deleteCouponUser() {
        log.info("删除用户失效180天以上的优惠券");
        // 删除用户失效半年以上的优惠券 参考京东
        couponUserService.deleteUnValidTimeCoupons(DateUtil.offsetDay(new Date(), -180));
    }

    /**
     * 改变用户优惠券的状态(设为失效状态)
     */
    @XxlJob("changeCouponUser")
    public void changeCouponUser() {
        Date now = new Date();
        log.info("设置用户的过期优惠券为失效状态");
        // 设置用户的过期优惠券为失效状态
        couponUserService.updateStatusByTime(now);
    }

    /**
     * 改变店铺优惠券的状态(设为过期状态)
     */
    @XxlJob("changeCoupon")
    public void changeCoupon() {
        Date now = new Date();
        log.info("设置店铺的过期优惠券为过期状态");
        // 查询需要更新的店铺id列表
        List<Long> shopIds = couponMapper.listOverdueStatusShopIds(now);
        // 取消投放
        couponService.changeCoupon(now);
        //清除缓存
        if (CollectionUtils.isNotEmpty(shopIds)) {
            for (Long shopId : shopIds) {
                cacheManagerUtil.evictCache("couponAndCouponProds", String.valueOf(shopId));
            }
        }
    }

    /**
     * 投放优惠券
     */
    @XxlJob("putOnCoupon")
    public void putOnCoupon() {
        Date now = new Date();
        log.info("投放优惠券");
        // 投放优惠券
        couponService.putonCoupon(now);
    }
}
